package com.itbac.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itbac.util.PayUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: BacHe
 * @email: 1218585258@qq.com
 * @Date: 2021/12/19 12:14
 */
@RestController
public class PayController {

    /**
     * 前端调这个接口, 创建微信支付订单
     * 拿到参数,用来前端直接调微信的接口: JSAPI调起支付API
     * https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_1_4.shtml
     */
    @PostMapping("/createOrder")
    public Map<String, String> createOrder(String openId, String outTradeNo, Long amount, String desc) throws Exception {
        return PayUtil.createOrder(openId, outTradeNo, amount, desc);
    }

    /**
     * 微信支付结果回调
     * 回调地址,在下单时要传给微信  http://www.test.com/callback
     * 在微信支付要配置域名:http://www.test.com
     */
    @PostMapping("/callback")
    public Map callback(HttpServletRequest request) {
        //时间戳
        String timestamp = request.getHeader("Wechatpay-Timestamp");
        //随机字符串
        String nonce = request.getHeader("Wechatpay-Nonce");
        //最新的证书序列号,会自动更新的那个证书
        String serial = request.getHeader("Wechatpay-Serial");
        //签名
        String signature = request.getHeader("Wechatpay-Signature");

        Map<String, String> rsp = new HashMap<>();
        rsp.put("code", "fail");
        rsp.put("message", "系统错误");
        try {

            BufferedReader reader = request.getReader();
            String str = null;
            StringBuilder body = new StringBuilder();

            while (null != (str = reader.readLine())) {
                body.append(str);
            }
            //响应主体: body
            System.out.println("builder:" + body.toString());

            //签名生成前的内容:
            StringBuilder signStr = new StringBuilder();
            //时间戳
            signStr.append(timestamp).append("\n");
            //随机字符串
            signStr.append(nonce).append("\n");
            //响应主体: body
            signStr.append(body.toString()).append("\n");

            //验证签名
            if (!PayUtil.signVerify(serial, signStr.toString(), signature)) {
                rsp.put("message", "sign error");
                return rsp;
            }
            //解密密文,得到明文json串 , 里面有支付结果,交易金额等信息
            String decryptOrder = PayUtil.decryptOrder(body.toString());
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(decryptOrder);
            //验证订单号,订单状态,订单金额 . 修改订单表的支付状态.
            //支付结果
            String trade_state = jsonNode.get("trade_state").textValue();
            //商户订单号
            String out_trade_no = jsonNode.get("out_trade_no").textValue();
            //支付金额
            long payer_total = jsonNode.get("amount").get("payer_total").asLong();

            //更新订单的支付状态


            rsp.put("code", "SUCCESS");
            rsp.put("message", "成功");


        } catch (IOException e) {
            e.printStackTrace();
        }

        return rsp;
    }
    /**
     *关闭订单
     */
    @PostMapping("/closeOrder")
    public String closeOrder(String outTradeNo) throws IOException {
        Boolean rsp = PayUtil.closeOrder(outTradeNo);
        return "结果:" + rsp;
    }
    /**
     * 查询订单支付状态
     */
    @PostMapping
    public String getOrder(String outTradeNo) throws Exception {
        return PayUtil.getOrder(outTradeNo);
    }
}
